<template>
  <div class="search-container">
    <form @submit.prevent="submit" class="middle-flex wrap-flex">
      <div class="form-item middle-flex">
        <span>搜索：</span>
        <a-input maxlength="10" v-model="formData.title" placeholder="请输入标题关键词"/>
      </div>
      <div class="form-item middle-flex">
        <span>类型：</span>
        <a-select
          @change="changeForm('', 'color')"
          style="min-width: 200px;"
          v-model="formData.cate_id"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="item in cateList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
        </a-select>
      </div>
      <div class="button-action middle-flex">
        <a-button htmlType="submit" style="margin-right: 5px;" type="primary">查询</a-button>
        <a-button @click="reset" style="margin-right: 5px;">重置</a-button>
        <div @click="visible = !visible" class="action-box">
          <span class="primary">{{visible ? '收起' : '展开'}}</span>
        </div>
      </div>
    </form>
    <div v-if="visible" class="middle-flex wrap-flex color-box">
      <strong>色系：</strong>
      <div
        class="cate-item"
        v-for="item in colorList"
        :class="{active: item.value === formData.color}"
        :key="item.value"
        @click="changeForm(item.value, 'color')"
      >{{item.label}}</div>
    </div>
  </div>
</template>

<script>
import * as Api from '@/api/goods'

export default {
  props: {
    payload: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      cateList: [],
      colorList: [],
      visible: this.payload.color || false,
      formData: { color: '', cate_id: '', ...this.payload }
    }
  },
  mounted() {
    this.fetchData()
    this.fetchColor()
  },
  methods: {
    async fetchData() {
      const cateList = await Api.cate()
      this.cateList = cateList
    },
    async fetchColor() {
      this.colorList = await Api.colorList()
    },
    submit() {
      this.$parent.saveParams(this.formData)
    },
    reset() {
      Object.keys(this.formData).map(key => {
        this.formData[key] = ''
      })
      Object.assign(this.formData, {
        page: 1,
        per_page: this.payload.per_page
      })
      this.submit()
    },
    changeForm(value, key) {
      this.formData[key] = value
      this.submit()
      // this.$emit("fetch", this.formData)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  margin-bottom: 20px;
}
.form-item {
  margin-right: 20px;
  white-space: nowrap;
}
.cate-item {
  padding: 0.2em 0.4em;
  margin-right: 3px;
  cursor: pointer;
  border-radius: 2px;
  &.active {
    background: @primary-color;
    color: white;
  }
}
.color-box {
  padding-top: 10px;
}
</style>
